package com.rongmei.jdsync.controller;

import com.rongmei.jdsync.dto.sync.PriceSyncResult;
import com.rongmei.jdsync.entity.PriceSyncLog;
import com.rongmei.jdsync.repository.PriceSyncLogRepository;
import com.rongmei.jdsync.response.ApiResponse;
import com.rongmei.jdsync.schedule.PriceSyncScheduler;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 价格同步控制器
 *
 * @author dongjun
 */
@RestController
@RequestMapping("/api/price-sync")
@Tag(name = "价格同步管理", description = "商品价格同步相关接口")
@Slf4j
public class PriceSyncController {

    @Autowired
    private PriceSyncScheduler priceSyncScheduler;

    @Autowired
    private PriceSyncLogRepository priceSyncLogRepository;


    /**
     * 手动触发价格同步
     */
    @Operation(summary = "手动触发价格同步", description = "立即执行一次价格同步任务")
    @PostMapping("/manual-sync")
    public ResponseEntity<?> manualPriceSync() {
        try {
            log.info("收到手动价格同步请求");
            PriceSyncResult result = priceSyncScheduler.manualPriceSync();
            return ResponseEntity.ok(ApiResponse.success(result));
        } catch (Exception e) {
            log.error("手动价格同步失败", e);
            return ResponseEntity.badRequest().body(ApiResponse.error(400, "手动价格同步失败: " + e.getMessage()));
        }
    }

    /**
     * 查询同步日志
     */
    @Operation(summary = "查询价格同步日志", description = "根据条件查询价格同步日志")
    @GetMapping("/logs")
    public ResponseEntity<?> getSyncLogs(
            @Parameter(description = "同步批次ID") 
            @RequestParam(required = false) String syncBatchId,
            
            @Parameter(description = "商品ID") 
            @RequestParam(required = false) Long goodsId,
            
            @Parameter(description = "同步状态：0-待同步，1-同步成功，2-同步失败") 
            @RequestParam(required = false) Integer syncStatus,
            
            @Parameter(description = "开始时间，格式：yyyy-MM-dd HH:mm:ss") 
            @RequestParam(required = false) 
            @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime startTime,
            
            @Parameter(description = "结束时间，格式：yyyy-MM-dd HH:mm:ss") 
            @RequestParam(required = false) 
            @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endTime) {
        
        try {
            List<PriceSyncLog> logs;
            
            if (syncBatchId != null) {
                logs = priceSyncLogRepository.findBySyncBatchId(syncBatchId);
            } else if (goodsId != null) {
                PriceSyncLog log = priceSyncLogRepository.findTopByGoodsIdOrderByCreateTimeDesc(goodsId);
                logs = log != null ? Collections.singletonList(log) : Collections.emptyList();
            } else if (syncStatus != null) {
                logs = priceSyncLogRepository.findBySyncStatus(syncStatus);
            } else if (startTime != null && endTime != null) {
                logs = priceSyncLogRepository.findByCreateTimeBetween(startTime, endTime);
            } else {
                // 默认查询最近100条记录
                logs = priceSyncLogRepository.findAll().stream()
                        .sorted((a, b) -> b.getCreateTime().compareTo(a.getCreateTime()))
                        .limit(100)
                        .collect(Collectors.toList());
            }
            
            return ResponseEntity.ok(ApiResponse.success(logs));
            
        } catch (Exception e) {
            log.error("查询同步日志失败", e);
            return ResponseEntity.badRequest()
                    .body(ApiResponse.error(400, "查询同步日志失败: " + e.getMessage()));
        }
    }

    /**
     * 查询同步统计信息
     */
    @Operation(summary = "查询同步统计信息", description = "根据批次ID查询同步统计信息")
    @GetMapping("/stats/{syncBatchId}")
    public ResponseEntity<?> getSyncStats(
            @Parameter(description = "同步批次ID") 
            @PathVariable String syncBatchId) {
        
        try {
            Object[] stats = priceSyncLogRepository.countSyncResultByBatchId(syncBatchId);
            
            if (stats != null && stats.length >= 3) {
                SyncStats syncStats = new SyncStats();
                syncStats.setSyncBatchId(syncBatchId);
                syncStats.setTotalCount(((Number) stats[0]).intValue());
                syncStats.setSuccessCount(((Number) stats[1]).intValue());
                syncStats.setFailedCount(((Number) stats[2]).intValue());
                syncStats.setPendingCount(syncStats.getTotalCount() - syncStats.getSuccessCount() - syncStats.getFailedCount());
                
                return ResponseEntity.ok(ApiResponse.success(syncStats));
            } else {
                return ResponseEntity.ok(ApiResponse.success("未找到该批次的同步记录"));
            }
            
        } catch (Exception e) {
            log.error("查询同步统计信息失败", e);
            return ResponseEntity.badRequest()
                    .body(ApiResponse.error(400, "查询同步统计信息失败: " + e.getMessage()));
        }
    }

    /**
     * 重试失败的同步记录
     */
    @Operation(summary = "重试失败的同步记录", description = "重新执行失败的价格同步记录  手动触发失败重试任务（用于测试和紧急处理）")
    @PostMapping("/retry-failed")
    public ResponseEntity<?> retryFailedSync(
            @Parameter(description = "最大重试次数，默认3次") 
            @RequestParam(defaultValue = "3") Integer maxRetryCount) {
        
        try {
            List<PriceSyncLog> failedLogs = priceSyncLogRepository.findFailedLogsForRetry(maxRetryCount);
            if (failedLogs.isEmpty()) {
                return ResponseEntity.ok(ApiResponse.success("没有需要重试的失败记录"));
            }
            log.info("找到 {} 条需要重试的失败记录", Integer.valueOf(failedLogs.size()));


            return ResponseEntity.ok(ApiResponse.success("重试任务已提交，共 " + failedLogs.size() + " 条记录"));
            
        } catch (Exception e) {
            log.error("重试失败的同步记录时发生错误", e);
            return ResponseEntity.badRequest().body(ApiResponse.error(400, "重试失败: " + e.getMessage()));
        }
    }









    /**
     * 同步统计信息DTO
     */
    public static class SyncStats {
        private String syncBatchId;
        private int totalCount;
        private int successCount;
        private int failedCount;
        private int pendingCount;

        // Getters and Setters
        public String getSyncBatchId() { return syncBatchId; }
        public void setSyncBatchId(String syncBatchId) { this.syncBatchId = syncBatchId; }

        public int getTotalCount() { return totalCount; }
        public void setTotalCount(int totalCount) { this.totalCount = totalCount; }

        public int getSuccessCount() { return successCount; }
        public void setSuccessCount(int successCount) { this.successCount = successCount; }

        public int getFailedCount() { return failedCount; }
        public void setFailedCount(int failedCount) { this.failedCount = failedCount; }

        public int getPendingCount() { return pendingCount; }
        public void setPendingCount(int pendingCount) { this.pendingCount = pendingCount; }
    }
}
